package pjkanri.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.sql.DataSource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

import pjkanri.entity.Account;
import pjkanri.entity.Project;

public class ProjectDAO {


	/**
	 * @param account
	 * @return
	 */
	public void insert(Project project) throws DAOException {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			
			project.setProject_id(getMaxId()+1);		
			
//			System.out.println("Project : " + project );
			session.save(project);
	}
	
	/**
	 * @param account
	 * @return
	 */
	public void update(Project prj) throws DAOException {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			
			Project project = (Project) session.get(Project.class, prj.getProject_id());
			
			project.setProject_name(prj.getProject_name());
			project.setProject_description(prj.getProject_description());
			
	}
	
	/**
	 * @return
	 * @throws DAOException
	 */
	private Integer getMaxId() throws DAOException{
		
		Integer maxId = 0;
		String sql = "SELECT Max(project_id) as max FROM project ";

		DataSource ds = DataSourceFactory.getDataSource();

		try (Connection conn = ds.getConnection();
				Statement pstmt = conn.createStatement()) {

			try (ResultSet rs = pstmt.executeQuery(sql)) {

				if (rs.next()) {
					if (rs.getString("max") == null ) return 0;
					maxId = Integer.parseInt(rs.getString("max"));
				}
			}

		} catch (SQLException e) {
			throw new DAOException(e);
		}
		return maxId;
	}
	
	/**
	 * Hibernateの使用
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Project> getProjectList()
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		Criteria criteria = session.createCriteria(Project.class);
		criteria.addOrder(Order.asc("project_id"));
		
		List<Project> listAccount = criteria.list();
		
		return listAccount;
	}
}
